
//创建一个pinia对象,存储token,以及token相关的方法(登录)

import { defineStore } from "pinia";
import { userLogin,UserForm , userInfo } from "@/api/user";
// interface StateInterface{
//     token:string
// }
let userPinia = defineStore({
    id:"userPinia",
    state: ()=>{
        return {
            token: localStorage.getItem("token") || "" , //存储的token,
            user:{
                name:"",
                avatarUrl:""
            }
        }
    },
    getters:{

    },
    actions:{
        //登录调用  api - userLogin -> token -> state - token 
        async doLogin(userForm:UserForm){
           let {code,data} = await userLogin(userForm);
           if(code == 200){
             this.token = data;
             //持久化,pinia刷新页面数据就丢失
             localStorage.setItem("token",data);
             //登录成功调用doUserInfo
             this.doUserInfo();
           }
        },
        async doUserInfo(){
            let {data} = await userInfo();
            this.user = data;
        },
        doLogout(){
            //清空
            this.token = "";
            this.user = {name:"",
                avatarUrl:""};
            localStorage.removeItem("token");    
            console.log("数据清空成功!!");
        }
    }
});


export default userPinia;